package com.ruyidd.config;

import com.sun.jna.Platform;
import jakarta.annotation.PostConstruct;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author tianxc
 * @Date 2024/5/17 13:15
 * @Description 项目启动的时候加载jacob.dll动态库
 */
@Component
public class JacobConfig {

    /**
     * 项目启动后执行加载
     */
    @PostConstruct
    public void loadJacobDll(){
        String jacobName = Platform.is64Bit()?"jacob-1.19-x64.dll":"jacob-1.19-x86.dll";
        ClassPathResource resource = new ClassPathResource("jacob/" + jacobName);
        File file = new File("jacob/" + jacobName);
        if(!file.exists()){
            File parentFile = file.getParentFile();
            if(!parentFile.exists()){
                parentFile.mkdirs();
            }
            try (
                    InputStream inputStream = resource.getInputStream();
                    FileOutputStream outputStream = new FileOutputStream(file);
            ){
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len=inputStream.read(buffer))>0){
                    outputStream.write(buffer,0,len);
                    outputStream.flush();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        System.setProperty("jacob.dll.path",file.getAbsolutePath());
        System.out.println("加载jacob.dll成功");
    }
}
